<!--
  @Description:新增/编辑导入任务数据航
  @Author: zqy
  @Date: 2020-12-09 11:26:58
  @Last Modified by:   zqy
  @Last Modified time: 2020-12-09 11:26:58
 -->
<template>
  <el-dialog
    v-el-drag-dialog
    ref="formDlg"
    :title="dlgTitle"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="clearForm"
    width="90%"
    append-to-body
    @close="closeDialog"
  >
    <div style="padding-right:30px">
      <el-form ref="refForm" :rules="formRules" :model="formData" size="mini" label-width="180px">
        <el-row>
          <el-col v-for="(item,index) in extColumnList" :key="index" :xs="24" :sm="12" :md="12" :lg="8" :xl="8">
            <el-form-item :label="`${item.name.replace('*','')}:`" :prop="item.code" :required="item.name.indexOf('*')>-1" :show-message="false">
              <el-input v-model="formData[item.code]" maxlength="200" :placeholder="`请输入${item.name.replace('*','')}`" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button size="mini" type="primary" @click="submitForm">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { saveImportData } from '../api'
import drag from '../../../../directives/el-drag-dialog/drag'
export default {
  name: 'ImportTaskDataEdit',
  directives:{
    'el-drag-dialog':drag
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    extColumnList: {
      type: Array,
      default: () => []
    },
    detailData: {
      type: [String, Object],
      default: ''
    },
    excelTaskId:{
      type:String,
      default:''
    },
    taskConfig:{
      type:Object,
      default:()=>{
        return {
          apiPrefix:'',// 应用接口前缀,如:ucenter,po-center,top-purchase
          checkRowApi:'',//行校验接口地址(后端提供)
          checkApi:'', //全量检查业务（自定义接口，后端提供）
          completeApi:'',//任务完成执行（回写业务操作）
          exportTempApi:'',// 临时数据导出接口
          taskFiltersRaw:[],  // 任务查询条件
          saveTempEmpty:false,// 是否保存null值为空字符串
          saveTempApi:'',//自定义临时数据保存接口
        }
      }
    }
  },
  data() {
    return {
      formData: {},
      formRules: {
        appName: [
          { required: true, message: '请选择应用名称', trigger: ['blur', 'change'] }
        ],
        serverKey: [
          { required: true, message: '请输入ID服务Key', trigger: 'blur' },
          { pattern: /^[a-z0-9_]+$/, message: '只能输入小写字母、下划线、数字' }
        ],
        cacheValue: [
          { required: true, message: '请输入缓存值', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '只能输入大于0的数字' }
        ],
        initValue: [
          { required: true, message: '请输入初始值', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '只能输入大于0的数字' }
        ],
        currentValue: [
          { required: true, message: '请输入当前序列值', trigger: 'blur' },
          { pattern: /^[1-9]\d*$/, message: '只能输入大于0的数字' }
        ]
      }
    }
  },
  computed: {
    dlgTitle() {
      return this.detailData && this.formData.id ? '编辑数据行' : '新增数据行'
    },
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  created() {
    this.$set(this.formData,'excelTaskId', this.excelTaskId)
    this.initFormData()
  },
  methods: {
    closeDialog() {
      this.dialogShow = false
      this.clearForm()
    },
    clearForm(done) {
      this.formData = {}
      this.$refs.refForm && this.$refs.refForm.resetFields()
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    // 初始化表单数据
    initFormData() {
      this.extColumnList.forEach(column => {
        const { code } = column
        let value = ''
        if(this.detailData ){
          if(![undefined,null].includes(this.detailData[code])){
            value = this.detailData[code]
          }
        }
        this.$set(this.formData, code, value)
      })
      if (this.detailData && this.detailData.id) {
        this.$set(this.formData, 'id', this.detailData.id)
      }
    },
    submitForm() {
      let empty = true
      for (const key in this.formData) {
        if (this.formData[key]) {
          empty = false
          break
        }
      }
      if (empty) {
        this.$message.warning('表单数据行不能全部为空')
        return
      }
      const  saveTempEmpty = this.taskConfig.saveTempEmpty===true

      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          const formData = Object.assign({}, this.formData)
          for(let key in formData){
            if([undefined,null].includes(formData[key])){
              formData[key]=''
            }
            formData[key] = `${formData[key]}`.trim()
            if(!saveTempEmpty){
              if( formData[key]===''){
                formData[key]=null
              }
            }
          }
          const saveTempApi = this.taskConfig.saveTempApi || ''
          saveImportData(this.taskConfig.apiPrefix,formData,saveTempApi).then(res => {
            if (res.success === 1) {
              this.$message({
                message: res.msg ? res.msg : `${formData.id ? '编辑' : '新增'}保存成功`,
                type: 'success'
              })
              this.closeDialog()
              //保存接口调用成功后，返回数据data为新增行或者编辑行的数据，为行编辑备用
              const id= formData.id || (res.data && res.data.id)
              const backParam={
                isNew:formData.id?false:true, // 新增操作成功后刷新到第一页，编辑刷新当前页
                id
              }
              this.$emit('success', backParam)
            }
          })
        }
      })
    }
  }
}
</script>
<style lang='scss' scoped>

</style>
